home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
NetNews Offline 2
/
NetNews Offline Volume 2.iso
/
news
/
comp
/
std
/
c
/
399
< prev
next >
Wrap
Internet Message Format
|
1996-08-06
|
3KB
Path: solon.com!not-for-mail
From: ok@cs.rmit.edu.au (Richard A. O'Keefe)
Newsgroups: comp.std.c,comp.lang.c.moderated
Subject: Re: Integral promotion.
Date: 15 Feb 1996 08:49:50 -0600
Organization: Comp Sci, RMIT, Melbourne, Australia
Sender: clc@solutions.solon.com
Approved: clc@solutions.solon.com
Message-ID: <4fvh6f$e29@solutions.solon.com>
References: <4fstj7$2l6@solutions.solon.com>
NNTP-Posting-Host: solutions.solon.com
X-Newsreader: NN version 6.5.0 #0 (NOV)
Rune Huseby <rune.huseby@gpi.telemax.no> writes:
>short test(short x1, short x2)
>{
> short result;
> result = x1 + x2; /* Warning: '=' : conversion from 'int '
> to 'short ', possible loss of data */
> return result;
>}
Your compiler is right. "Integral promotion" means that before anything
else happens to them in an arithmetic expression, signed char and short
promote to int, and unsigned char and unsigned short promote to unsigned int.
Your compiler has to be able to implement arithmetic on
signed int signed long
unsigned int unsigned long
but not on any other integral types. Note in particular that in a system
where INT_MAX > SHRT_MAX loss of data really _is_ possible:
short x1 = SHRT_MAX;
short x2 = SHRT_MAX;
short result = x1 + x2; /* OVERFLOW! */
On a 16-bit sloppy system, the chances are pretty good that you'd get
result < 0
but on a 32-bit system, sloppy or not, this example must yield
result > 0.
And remember, on a MIPS, Alpha, SPARC, 88k, &c there _is_ no 16-bit add
instruction; it _has_ to be done in 32-bit mode.
Yes, there are C compilers that generate code that raises an exception if
a signed integer overflow occurs. I've used one. It's *extremely* useful
because it's almost always a mistake. If you really want wraparound, you
can use unsigned arithmetic.
>The reason I ask is that I am writing code that should be
>portable from a 16-bits environment (where short and int are the
>same size) to a 32-bits environment. (My 16-bits compiler does
>not complain about the code).
Well, there's no way to get exactly the same set of warnings on every
system; a compiler can legitimately complain about the colour of your
eyes if it wants to, as long as it correctly translates the code.
It is really really worth investing in a 'lint' checker. If you're using
a DOS system, I've heard good things about Gimpel's lint.
--
Election time; but how to get Labour _out_ without letting Liberal _in_?
Richard A. O'Keefe; http://www.cs.rmit.edu.au/~ok; RMIT Comp.Sci.